package serveletpackage;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.arl.jaf.Agent;
import org.arl.jaf.web.JafPlugin;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.omg.CORBA.RepositoryIdHelper;

public class HelloHandler extends AbstractHandler {

	JafPlugin jaf = new JafPlugin();

	public void handle(String target, Request baseRequest,
			HttpServletRequest request, HttpServletResponse response)
					throws IOException, ServletException {

		System.out.println(" handler is being called");
		System.out.println(" hello world");
		// the value passed in from the client side
		String value = request.getParameter("value");
		int option = Integer.parseInt(value);
		response.setContentType("text/html;charset=utf-8");
		response.setStatus(HttpServletResponse.SC_OK);
		baseRequest.setHandled(true);

		switch (option) {
		case 1:
			jaf.intiatePlatform();
			response.getWriter().println("Platform Started");
			response.getWriter().println("Server Registered");
			break;
		case 2:
			System.out.println("Agent Name");
			Agent[] a = jaf.getAllAgents();
			System.out.println(" obtained list of agents");
			for (Agent indiAgent : a ){
				response.getWriter().println("Agent Name:"+indiAgent.getName());
			}
			break;
		case 3:
			String clientName= request.getParameter("clientname");
			System.out.println(" "+clientName);
			boolean creationStatus=jaf.createDummyclient(clientName);
			response.getWriter().println("Agent creation status"+creationStatus);
			break;
		case 4:
			//			jaf.initiateRequest(arguments.get(0).getOptionParameter(),
			//					arguments.get(0).getRequestMessage());
			break;
		case 5:
			System.out.println(" Terminating Services.....");

			jaf.terminatePlatform();
			break;
		default:
			response.getWriter().println("Incorrect Option");

		}

		// do stuff with that here

		// return a response

		// this gets sent back down to the client-side and is alerted
		//		response.getWriter().println("<h1>Hello World</h1>");
	}


	private String[] AgenttoString(Agent[] a) {
		System.out.println(" "+a.length);

		String[] agentName = null;
		int i = 0;
		for ( i=0;i<a.length;i++){
			Agent inAgent= a[i];
			System.out.println(" "+inAgent.getName());
			agentName[i]= inAgent.getName();
		}	

		//		for (Agent indiAgent : a) {
		//			agentName[i] = indiAgent.getName();
		//			i++;
		//		}
		return agentName;

	}

}
